import axios, { AxiosHeaders } from "@ohos/axios";
import { HttpAdapter } from "../HttpAdapter";
import { Request } from "../Reqest";
import { Response } from "../Response";

export class AxiosAdapter implements HttpAdapter {

  constructor() {
    //axios日志
    /**
     * axios拦截器
     */
    axios.interceptors.request.use(function (config) {
      console.log('请求参数：', JSON.stringify(config));
      return config;
    }, error => {
      return Promise.reject(error);
    });
    axios.interceptors.response.use(function (response) {
      console.log('返回结果：', JSON.stringify(response));
      return response;
    }, error => {
      console.log('返回错误：', error);
      return Promise.reject(error);
    });
  }

  call(request: Request): Promise<Response<any>> {
    let header: AxiosHeaders = new AxiosHeaders();
    for (let [key, value] of request.header) {
      header.set(key, value);
    }
    return axios.request({
      url: request.URL.toString(),
      method: request.method,
      headers: header,
      params: request.query,
      data: request.body
    }).then(function (response) {
      let header = new Map<string, string>();
      Object.keys(response.headers).forEach(key => {
        header.set(key, response.headers[key]);
      });
      return new Response(response.status, header, response.data, response);
    });
  }
}